<?php
namespace App\Http\Controllers\AppApi\Order;

use App\Http\Controllers\AppApi\BaseController as Controller;
use App\Jobs\Fun;
use App\Models\Admin\OrderBaleModel;
use App\Models\Admin\OrderCheckModel;
use App\Models\Admin\OrderTempModel;
use App\Models\CompanysModel;
use App\Models\OrderCommentModel;
use App\Models\User\UserModel;
use App\Models\User\UserOrdersModel;
use App\Repositories\Admin\OrderBaleRepository;
use App\Services\Admin\OrderBaleService;
use Illuminate\Http\Request;

class MyOrderController extends Controller
{
    protected $bale;

    public function __construct(Request $request)
    {
        parent::__construct();
        $this->bale = new OrderBaleService();
        $this->orderBaleRepository = new OrderBaleRepository();
        if (!$request->token) {
            return $this->returnJson(-2,'参数错误');
        }
        $this->uid = $this->accessGet($request->token);
        if(!$this->uid){
            return $this->returnJson(-13,'您未登录或未注册');
        }
        $type = UserModel::where('id',$this->uid)->value('type');
        if(!in_array($type,[2,3,4])){
            return $this->returnJson(-97,'您没有权限查看此目录');
        }
    }

    /**
     * 我的订单（抢单和生产的订单，前期不需要分页）
     * /api/order/my/get?
     */
    public function getOrderList()
    {
       /// \DB::enableQueryLog();
        $orderTempArr = [];
        $orderArr = [];
        $orderTemp = OrderTempModel::with('orderDetail')->where('fid',$this->uid)
           // ->where('status','!=',4)
           ->orderBy('id','DESC')
            ->get();
       /// $sql=\DB::getQueryLog();  print_r($sql);exit;



     //   $order = UserOrdersModel::with('orderDetail')->where('fid',$this->uid)->get();



        //status 1抢单中
        if($orderTemp){
            $orderTemp = $orderTemp->toArray();
        }else{
            $orderTemp=[];
        } 
        foreach ($orderTemp as $t){
            $item['id'] = $t['bale'];
            $item['company'] = CompanysModel::where('uid',$t['cid'])->value('com_name');
            $item['title'] = $t['order_detail']['name']??'';
            $item['addtime'] = $t['created_at'] ? date('Y-m-d H:i:s',$t['created_at']) : '';
            $item['exptime'] = $t['order_detail']['period'] ? date('Y-m-d H:i:s',$t['order_detail']['period']) : '';
            $item['img'] =Fun::pImg($t['order_detail']['img']);
            $item['status'] = 0; //生产订单的流程状态 0 不显示
            $item['order_status'] = $t['status']; //抢单中还是生产中  1未支付，2已支付未抢单，3抢单中，4抢单成功  5抢单失败
            $item['is_del'] = $t['order_detail']['del']; // 1删除（已取消）
            $item['type'] = 1;
            if($t['created_at']+OrderTempModel::MaxTime>time()){
                $item['out_trade_no']=$t['out_trade_no'];
            }else{
                $item['out_trade_no']='';
            }


            $orderTempArr[] = $item;
        }
       /* if($order){
            $order = $order->toArray();
        }else{
            $order=[];
        }

        foreach ($order as $o){
            $item['id'] = $o['bale'];
            $item['company'] = CompanysModel::where('uid',$o['cid'])->value('com_name');
            $item['title'] = $o['order_detail']['name'];
            $item['addtime'] = $o['created_at'] ? date('Y-m-d H:i:s',$o['created_at']) : '';
            $item['exptime'] = $o['order_detail']['period'] ? date('Y-m-d H:i:s',$o['order_detail']['period']) : '';
            $item['img'] = $o['order_detail']['img'];
            $item['status'] = $o['status']; //订单状态：1未发原料，2接收原料，3生产中，4客户跟单，5确认跟单，6打包发货，7到货签收，8评价
            $item['order_status'] = 4;
            $item['is_del'] = $o['order_detail']['del']; // 1删除（已取消）
            $item['type'] = 2;
            $orderArr[] = $item;
        }*/
        $list = array_merge($orderTempArr,$orderArr);
        return $this->toJSON(0,$list);
    }

    /**
     * 我的订单（我的发布）
     */
    public function pushOrderList()
    {
        $orderBealArr = [];
        $orderBeal = OrderBaleModel::with('orderTemp')->where('uid',$this->uid)->get();
        $orderBeal = $orderBeal->toArray();
        foreach ($orderBeal as $t){
            $item['id'] = $t['id'];
            $item['company'] = '';
            $item['title'] = $t['name'];
            $item['addtime'] = $t['created_at'] ? date('Y-m-d H:i:s',$t['created_at']) : '';
            $item['exptime'] = $t['period'] ? date('Y-m-d H:i:s',$t['period']) : '';
            $item['img'] = $t['img'];
            $item['status'] = $t['status']; //生产订单的流程状态 0 不显示
            //$item['order_status'] = $t['status']; //1未开始抢单(草稿中)，2抢单中，3已完成抢单
            $item['is_del'] = $t['del']; // 1删除（已取消）
            if($t['status'] == 2){  //抢单中，取出抢单公司数量
                $count = OrderTempModel::where(['bale'=>$t['id']])->count();
                $item['company'] = $count ? $count.' 家工厂正在抢单' : '0家工厂正在抢单';
            }elseif($t['status'] == 3){ //已完成抢单 取出抢单公司名称
                $company = CompanysModel::where('uid',$t['order_temp']['fid'])->value('com_name');
                $item['company'] = $company ? $company : '';
                $order_status=UserOrdersModel::where('bale',$t['id'])->value('status');
                $item['order_status'] = $order_status ? $order_status : 0;  //订单状态：1未发原料，2接收原料，3生产中，4客户跟单，5确认跟单，6打包发货，7到货签收，8评价
            }
            $orderBealArr[] = $item;
        }

        return $this->output($orderBealArr,'ok');
    }

    /**
     * 发布订单
     */
    public function pushOrder(Request $request)
    {
        $id = intval($request->input('id',0));
        if(!$id){
            return $this->toJSON(-2);
        }
        $orderBeal = OrderBaleModel::where('id',$id)->first();
        if(!$orderBeal){
            return $this->toJSON(-3);
        }
        if($orderBeal->status !=1){
            return $this->output([],'已经是发布状态',-100);
        }
        $orderBeal->status = 2;
        if($orderBeal->save()){
            return $this->toJSON(0);
        }
        return $this->toJSON(-100);
    }

       /**
     * 改变订单状态
     * @param Request $request
     * @return array
     */
    public function updateOrder(Request $request)
    {
        $id = intval($request->input('id',0));
        if(!$id){
            return $this->toJSON(-2);
        }
        $orderBeal = OrderBaleModel::where('id',$id)->first();
        if(!$orderBeal){
            return $this->toJSON(-3);
        }
        $userOrder = UserOrdersModel::where('bale',$id)->first();
        if(!$userOrder){
            return $this->toJSON(-3);
        }
        /**
         * type
         * 1. 发出原料
         * 2. 接收原料
         * 4. 跟单开始
         * 5. 确认跟单
         * 6. 打包发货
         * 7. 确认收货
         * 8. 评价
         */
        $type = intval($request->input('type',0));
        if(!$type){
            return $this->toJSON(-2);
        }
        switch ($type){
            case 1:  $status=2;break;
            case 2:  $status=3;break;
            case 3:  $status=4;break;
            case 4:  $status=5;break;
            case 5:  $status=6;break;
            case 6:  $status=7;break;
            case 7:  $status=8;break;
            default : break;
        }
        if(!$status){
            return $this->toJSON(-2);
        }
        $userOrder->status = $status;
        if($userOrder->save()){
            return $this->toJSON(0);
        }else{
            return $this->toJSON(-100);
        }
    }

    /**
     * 订单评价
     * @param Request $request
     * @return array
     */
    public function commentOrder(Request $request)
    {
        $id = intval($request->input('out_trade_no',0));
        if(!$id){
            return $this->toJSON(-2);
        }
        $content = trim($request->input('content',0));
        $level = intval($request->input('level',0));    //0一般 1良好 2很好 3差 4很差

        $orderComment = OrderCommentModel::where('out_trade_no',$id)
            ->where('uid',$this->uid)
            ->count();
        if($orderComment){
            return $this->output([],'你已经评价过了',500);
        }
        $order=UserOrdersModel::where(['order_no'=>$id])->select('order_no','fid','cid')->first();
        $type=null;
        if($order->fid==$this->uid){
            $type=OrderCommentModel::type_gongchang;
        }elseif($order->cid==$this->uid){
            $type=OrderCommentModel::type_gongsi;
        }else{
            return $this->output([],'权限错误',500);
        }
        $insertData = [
            'out_trade_no'=>$id,
            'uid'=>$this->uid,
            'content'=>$content,
            'level'=>$level,
            'addtime'=>time(),
            'type'=>$type
        ];

        if(OrderCommentModel::insert($insertData)){
            //把用户的订单信息改成已完成
             UserOrdersModel::where('order_no',$id)->update(['status'=>UserOrdersModel::status_pingjia]);

            return $this->output([],'评价成功',200);
        }else{
            return $this->output([],'评价失败',500);
        }
    }

    /**
     * 跟单开始
     * @param Request $request
     * @return array
     */
    public function startOrder(Request $request)
    {
        $id = intval($request->input('id',0));
        if(!$id){
            return $this->toJSON(-2);
        }
        $orderBeal = OrderBaleModel::where('id',$id)->first();
        if(!$orderBeal){
            return $this->toJSON(-3);
        }

    }


    /**
     * 订单详情
     * @param Request $request
     * @return array
     * /api/order/my/detail
     * @deprecated
     */
    public function orderDetail(Request $request)
    {

        $id = intval($request->input('id',0));
        if(!$id){
            return $this->output([],'参数不全',500);
        }
   //     var_dump($this->uid);exit;
        $arr = [];
        $order = UserOrdersModel::with('orderFactory')->with('orderDetail')->where('bale',$id)->where('fid',$this->uid)->first();
        if(!$order){
            return $this->output([],'数据不存在',500);
        }
      //  print_r($order->toArray());exit;
        $arr['oid'] = $order['bale'] ?? 0;
        $arr['cid'] = $order['cid'] ?? 0;
        $arr['fid'] = $order['fid'] ?? 0;
        $arr['uid'] = $this->uid;
        $arr['user_oid'] = $order['id'] ?? 0;
        $arr['com_name'] = $order['orderFactory']['com_name'] ?? '';   //中单企业
        $arr['com_address'] = $order['orderFactory']['com_address'] ?? ''; //企业地址
        $arr['legal_name'] = $order['orderFactory']['legal_name'] ?? '';  //企业负责人
        $arr['legal_mobile'] = $order['orderFactory']['legal_mobile'] ?? ''; //负责人手机
        $arr['num'] = $order['num'] ?? 0;    //订单数量
        $arr['money'] = $order['money'] ?? 0; // 订单金额
        $arr['all_money'] = $arr['num'] * $arr['money'];
        $arr['note'] = $order['note'] ?? '';
        $arr['created_at'] = $order['created_at'] ? date('Y-m-d H:i:s',$order['created_at']) : '';
        $arr['kd_name'] = $order['kd_name'] ?? '';
        $arr['kd_code'] = $order['kd_code'] ?? '';
        $arr['kd_time'] = $order['kd_time'] ?? 0;
        $arr['status'] = '';
        $arr['other'] = $order['kd_code'] ? json_encode($order['other'] ) : [];
        $arr['img'] = $order['orderDetail']['img'] ?? '';
        $arr['detail'] = $order['orderDetail']['detail'] ?? '';
        $arr['send_address'] = '杭州';
        $arr['revice_address'] = '上海';
        //查询评价
        $orderFacComment = OrderCommentModel::where(['oid'=>$id,'uid'=>$this->uid])->value('content');
        $orderComComment = OrderCommentModel::where(['oid'=>$id,'uid'=>$order['cid']])->value('content');
        $arr['orderFacComment'] = $orderFacComment ? $orderFacComment : '';
        $arr['orderComComment'] = $orderComComment ? $orderComComment : '';

        return $this->output($arr,'ok',200);
    }




    /**
     * 订单报告
     * @param Request $request
     * @return array
     */
    public function orderReport(Request $request)
    {
        $id = intval($request->input('id',0));
        if(!$id){
            return $this->output([],'参数不全',500);
        }
        $orderCheck = OrderCheckModel::where('order',$id)->where('del',0)->first();
        if(!$orderCheck){
            return $this->output([],'数据不存在',500);
        }
        $orderCheck['stylelist'] = json_decode($orderCheck['stylelist'],true);
        $orderCheck['sizelist'] = json_decode($orderCheck['sizelist'],true);
        $orderCheck['thrumlist'] = json_decode($orderCheck['thrumlist'],true);

        return $this->output($orderCheck,'ok',200);
    }
}
